<template>
  <div>
    <form v-if="tokens" class="w-50 m-auto mt-5">
      <div class="mb-3">
        <label for="field1" class="form-label">Тема</label>
        <input
          type="text"
          :class="'form-control ' + get_msg_class('topic')"
          id="field1"
          aria-describedby="emailHelp"
          v-model="topic"
        />
        <div class="invalid-feedback">
          {{ get_msg("topic") }}
        </div>
      </div>
      <div class="mb-3">
        <label for="field2" class="form-label">Подробности</label>
        <vue-easymde
          id="field2"
          v-model="description"
          :options="{
            lineNumbers: true,
            renderingConfig: {
              codeSyntaxHighlighting: true,
            },
            showIcons: ['code', 'undo', 'redo'],
            spellChecker: false,
            styleSelectedText: false,
          }"
        />
      </div>

      <!-- <div class="mb-3 form-check">
      <input type="checkbox" class="form-check-input" id="exampleCheck1" />
      <label class="form-check-label" for="exampleCheck1">Check me out</label>
    </div> -->
      <button
        type="button"
        class="btn btn-primary"
        @click="sendForm(tokens.access_token)"
      >
        Отправить
      </button>
    </form>
    <vue-basic-alert :duration="500" :closeIn="5000" ref="alert" />
  </div>
</template>

<script>
import VueBasicAlert from "vue-basic-alert";

export default {
  props: {
    tokens: Object,
    user: Object,
  },
  data() {
    return {
      topic: "",
      description: "",
      detail: [],
    };
  },
  components: {
    VueBasicAlert
  },
  methods: {
    get_msg_class(name) {
      let ans = "";
      this.detail.forEach((el) => {
        if (el.loc[1] == name) {
          ans = "is-invalid";
        }
      });
      return ans;
    },
    get_msg(name) {
      let ans = "";
      this.detail.forEach((el) => {
        if (el.loc[1] == name) {
          ans = el.msg;
        }
      });
      return ans;
    },
    sendForm(token) {
      this.detail = [];
      fetch(`${process.env.VUE_APP_BASE_URI}/req/create`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          topic: this.topic,
          description: this.description,
        }),
      }).then(
        (resp) => {
          if (resp.status != 500) {
            resp.json().then(
              (body) => {
                if (resp.ok) {
                  this.detail = [];
                  this.topic = "";
                  this.description = "";
                  this.$refs.alert.showAlert(
                    "success",
                    "Вы успешно отпарвили заявление. Ждите обработки",
                    "Отправлено"
                  );
                } else {
                  this.$refs.alert.showAlert(
                    "error",
                    `${resp.statusText}`,
                    "Ошибка"
                  );
                }
                if (resp.status == 422) {
                  this.detail = body.detail;
                }
              },
              () => {
                this.$refs.alert.showAlert(
                  "error",
                  "Ошибка сервера",
                  "Ошибка обработки json"
                );
              }
            );
          } else {
            this.$refs.alert.showAlert("error", "Ошибка сервера", "500 error");
          }
        },
        (err) => {
          this.$refs.alert.showAlert("error", "Ошибка сервера", err.message);
        }
      );
    },
  },
};
</script>

<style>
.editor-toolbar.fullscreen {
  z-index: 1030 !important;
}
.EasyMDEContainer .CodeMirror-fullscreen {
  z-index: 1030 !important;
}
.editor-preview-side {
  z-index: 1030 !important;
}
</style>